//
//  UserCenterViewController.m
//  QRMaster
//
//  Created by lc on 16/4/28.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "UserCenterViewController.h"
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "StartPageController.h"
#import "Reachability.h"
#import "UIImageView+WebCache.h"
#import "ChangeHeadImgViewController.h"
#import "OpertionPlist.h"
#import "Base64.h"
#import "KeychainItemWrapper.h"
#import "userInfoModel.h"
#import "UserInfoLogic.h"
#import "MJExtension.h"
#import "SystemSetViewController.h"
#import "FeedBackViewController.h"
#import "RecoderShareCardController.h"
#import "ChangeHeadImgViewController.h"
#import "GeneralSettingViewController.h"
#import "QRSingleton.h"
#import "PersonalTodayShareCardController.h"

@interface UserCenterViewController ()

@property (nonatomic,assign) NSInteger tokenCount;
@property (nonatomic,strong) NSUserDefaults * userInfo;
@property (nonatomic,copy) NSString * headurl;

@end

@implementation UserCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    
    [self getData];
    
    [self prepareMainView];
    
    UITapGestureRecognizer * headChangeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeHeadImage)];
    [_headImage addGestureRecognizer:headChangeTap];
    
    UITapGestureRecognizer * shareTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shareTap)];
    [_shareView addGestureRecognizer:shareTap];

}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //从本地数据库读取数据
    [self getDataFromDisk];
    
    self.navigationItem.title = NSLocalizedString(@"mine", nil);
    
//    _roleLabel.text = [QRSingleton sharedQRSingleton].roleName;
    NSString * roleTitle = [QRSingleton sharedQRSingleton].roleName;
    if ([roleTitle isEqualToString:@"超级管理员"]){
        _roleLabel.text = NSLocalizedString(@"manager", nil);
    }else if ([roleTitle isEqualToString:@"子管理员"]){
        _roleLabel.text = NSLocalizedString(@"groupManagement", nil);
    }else if ([roleTitle isEqualToString:@"普通职员"]){
        _roleLabel.text = NSLocalizedString(@"general", nil);
    }else if ([roleTitle isEqualToString:@"组管理员"]){
        _roleLabel.text = NSLocalizedString(@"groupManager", nil);
    }else{
        _roleLabel.text = NSLocalizedString(@"general", nil);
    }
    
    
    _feedBackLabel.text = NSLocalizedString(@"feedBack", nil);
    _settingLabel.text = NSLocalizedString(@"mineSetting", nil);
    _kefuLabel.text = NSLocalizedString(@"ServiceTelePhone", nil);
    _myRoleLabel.text = NSLocalizedString(@"myRole", @"我的角色");
    _roomShareLabel.text =  NSLocalizedString(@"shareList", nil);
    
    [self prepareMainView];

}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    self.navigationItem.title=NSLocalizedString(@"mine", nil);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenCheck) name:@"tokenCheck"  object:nil];
    
    
}

- (void)prepareMainView{
        
    
    _feedbackBtn.frame = CGRectMake(_feedbackBtn.frame.origin.x, _feedbackBtn.frame.origin.y, UI_SCREEN_WIDTH/3, _feedbackBtn.frame.size.height);
     _settingBtn.frame = CGRectMake(_settingBtn.frame.origin.x, _settingBtn.frame.origin.y, UI_SCREEN_WIDTH/3, _settingBtn.frame.size.height);
     _customerServicesBtn.frame = CGRectMake(_customerServicesBtn.frame.origin.x, _customerServicesBtn.frame.origin.y, UI_SCREEN_WIDTH/3, _customerServicesBtn.frame.size.height);
    
    
    _headImage.layer.cornerRadius = _headImage.frame.size.width/2;
    _headImage.layer.masksToBounds = YES;
    _headImage.userInteractionEnabled = YES;
    
    //设置边框
    [_headView.layer setBorderWidth:0.5];
    _headView.layer.borderColor = [UIColorFromRGB(0xc1c1c1) CGColor];
    
    [_middleView.layer setBorderWidth:0.5];
    _middleView.layer.borderColor = [UIColorFromRGB(0xc1c1c1) CGColor];
    
    [_roleView.layer setBorderWidth:0.5];
    _roleView.layer.borderColor = [UIColorFromRGB(0xc1c1c1) CGColor];
    
    [_shareView.layer setBorderWidth:0.5];
    _shareView.layer.borderColor = [UIColorFromRGB(0xc1c1c1) CGColor];

    
}

-(void)getDataFromDisk
{
    __block userInfoModel *userModel = [[userInfoModel alloc]init];
    UserInfoLogic *userLogic = [[UserInfoLogic alloc]init];
    
    [userLogic queryUserInfo:^(userInfoModel *myUserModel)
     {
         userModel =myUserModel;
     }
     ];
    
    //头像
    _headurl = userModel.headUrl;
    [_headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HEADERURL,userModel.headUrl]] placeholderImage:[UIImage imageNamed:@"96人像"]];
    
    //用户名
//    DDLOG(@"用户名=%@",userModel.name);
    _nameLabel.text = userModel.name;
    [_nameLabel sizeToFit];
    
    //手机号码
    _phoneLabel.text = userModel.mobile;
    
    //性别
    if ([userModel.gender intValue]==1){
        _sexImage.image = [UIImage imageNamed:@"male-blue"];
    }else{
        _sexImage.image = [UIImage imageNamed:@"female-red"];
    }
    
    

}



//获取个人信息
-(void)getData;
{
    if ([self IsHaveNetwork]) {
        return;
    }
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];

    [postDict setValue:UID forKey:@"id"];
    [postDict setValue:TOKEN forKey:@"token"];
    RequestNetWork * rn = [[RequestNetWork alloc]init];
    [rn initWithPath:POST(GETINFO) params:postDict block:^(id downLoadData, id error) {

        if ([downLoadData objectForKey:@"data"] != nil) {
            
//            DDLOG(@"data = %@",downLoadData[@"data"]);
            [self analysisUserInfoData:[downLoadData objectForKey:@"data"]];
            
        }
        else if (error != nil) {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        
    }];

}

-(void)analysisUserInfoData:(NSDictionary *)data
{
    userInfoModel *userModel = [userInfoModel mj_objectWithKeyValues:data];
    userModel.uid=[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"];
    UserInfoLogic *userLogic = [[UserInfoLogic alloc]init];
    [userLogic deleteTable];
    [userLogic insertUserInfo:userModel];
    
    NSString * gesture = [data objectForKey:@"gesture"];
    //    保存手势密码
    if (![gesture isEqualToString:@""]) {
        NSString * decodeString = [NSString stringWithFormat:@"%@",[gesture base64DecodedString]];
        [_userInfo setValue:decodeString forKey:GUESTUREKEY];
    }
    
    //从本地数据库读取数据
    [self getDataFromDisk];
}


#pragma mark - 通知方法，检查token值
-(void)tokenCheck
{
    @try {
        _tokenCount ++;
        if (_tokenCount == 1) {
            StartPageController * spc = [[StartPageController alloc]init];
            [[self topViewController] presentViewController:spc animated:YES completion:^{
                [PromptInfoView showMessage:NSLocalizedString(@"errorToken", nil)];
            }];
        }
    }
    @catch (NSException *exception) {
        StartPageController * spc = [[StartPageController alloc]init];
        [self presentViewController:spc animated:YES completion:^{
            [PromptInfoView showMessage:NSLocalizedString(@"errorToken", nil)];
        }];
    }
}

#pragma mark - 解决视图问题
- (UIViewController*)topViewController
{
    return [self topViewControllerWithRootViewController:self];
}


- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController
{
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabBarController = (UITabBarController *)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}


#pragma mark --点击事件
//改变头像
- (void) changeHeadImage{
    ChangeHeadImgViewController * chivc = [[ChangeHeadImgViewController alloc]init];
    chivc.imageUrlPath = _headurl;
    chivc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chivc animated:YES];
    chivc.selectImgPath = ^(NSInteger imgPath)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%ld.png",(long)imgPath]];
        _headImage.image = [UIImage imageWithContentsOfFile:filePath];
        NSDictionary * dataDict = [OpertionPlist readDataFromPlist];
        NSArray * imgArray = [dataDict objectForKey:HEADERIMG];
        _headurl = [NSString stringWithFormat:@"%@",imgArray[imgPath]];
        
        [self getData];
    };
    
    chivc.postImgPath = ^(NSString * postImgPath)
    {
        _headurl = [NSString stringWithFormat:@"%@",postImgPath];
        //        [titleImgView sd_setImageWithURL:[NSURL URLWithString:headurl] placeholderImage:[UIImage imageNamed:@"96人像"]];
        
        [self getData];
    };

}

//跳转到分享记录页面
- (void) shareTap{
//    RecoderShareCardController * rsc = [[RecoderShareCardController alloc]init];
    PersonalTodayShareCardController * ptvc = [[PersonalTodayShareCardController alloc] init];
    ptvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:ptvc animated:YES];
}


- (IBAction)feedBack:(UIButton *)sender {
    FeedBackViewController * fbvc = [[FeedBackViewController alloc]init];
    fbvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:fbvc animated:YES];
}

- (IBAction)generalSetting:(UIButton *)sender {
    GeneralSettingViewController * settingVC = [[GeneralSettingViewController alloc]init];
    settingVC.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:settingVC animated:YES];
    
//    SystemSetViewController * settingVC = [[SystemSetViewController alloc]init];
//    settingVC.hidesBottomBarWhenPushed=YES;
//    [self.navigationController pushViewController:settingVC animated:YES];
}

- (IBAction)customerServices:(UIButton *)sender {
    NSString *telUrl = [NSString stringWithFormat:@"telprompt://020-32209192"];
    NSURL *url = [NSURL URLWithString:telUrl];
    [[UIApplication sharedApplication] openURL:url];

}



-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
